document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const readClipboardBtn = document.getElementById('readClipboard');
    const reloadClipboardBtn = document.getElementById('reloadClipboard');
    const prevSentenceBtn = document.getElementById('prevSentence');
    const nextSentenceBtn = document.getElementById('nextSentence');
    const showProgressBtn = document.getElementById('showProgress');
    const sentenceElement = document.getElementById('sentence');
    const progressIndicator = document.getElementById('progressIndicator');
    
    // 创建提示元素
    const endNotification = document.createElement('div');
    endNotification.className = 'end-notification';
    endNotification.textContent = '到头了~';
    document.querySelector('.content').appendChild(endNotification);
    
    // 存储分割后的句子和当前句子索引
    let sentences = [];
    let currentIndex = 0;
    
    // 自动翻页计时器
    let autoNextTimer = null;
    let countdownValue = 10;
    let originalNextBtnText = '下一句 →';
    
    // 显示"到头了"提示
    function showEndNotification() {
        endNotification.style.display = 'block';
        setTimeout(() => {
            endNotification.style.display = 'none';
        }, 1500);
    }
    
    // 开始自动翻页倒计时
    function startAutoNextCountdown() {
        // 清除可能存在的旧计时器
        if (autoNextTimer) {
            clearInterval(autoNextTimer);
        }
        
        // 如果已经是最后一句，不启动计时器
        if (currentIndex >= sentences.length - 1) {
            nextSentenceBtn.textContent = originalNextBtnText;
            return;
        }
        
        countdownValue = 10;
        updateNextButtonText();
        
        autoNextTimer = setInterval(() => {
            countdownValue--;
            updateNextButtonText();
            
            if (countdownValue <= 0) {
                // 自动触发下一句
                if (currentIndex < sentences.length - 1) {
                    currentIndex++;
                    updateSentenceDisplay();
                    updateButtonStates();
                    
                    // 如果不是最后一句，重新开始倒计时
                    if (currentIndex < sentences.length - 1) {
                        countdownValue = 10;
                        updateNextButtonText(); // 立即更新按钮文字，避免显示(0s)
                    } else {
                        // 是最后一句，停止计时器
                        clearInterval(autoNextTimer);
                        autoNextTimer = null;
                        nextSentenceBtn.textContent = originalNextBtnText;
                    }
                } else {
                    // 已经是最后一句，停止计时器
                    clearInterval(autoNextTimer);
                    autoNextTimer = null;
                    nextSentenceBtn.textContent = originalNextBtnText;
                }
            }
        }, 1000);
    }
    
    // 增加倒计时时间
    function addCountdownTime(seconds) {
        if (autoNextTimer && currentIndex < sentences.length - 1) {
            countdownValue += seconds;
            updateNextButtonText();
        }
    }
    
    // 更新下一句按钮文字
    function updateNextButtonText() {
        nextSentenceBtn.textContent = `下一句(${countdownValue}s↑) →`;
    }
    
    // 读取剪切板内容
    readClipboardBtn.addEventListener('click', async function() {
        try {
            const text = await navigator.clipboard.readText();
            if (text) {
                processSentences(text);
            } else {
                sentenceElement.textContent = "剪切板为空，请复制内容后再试";
            }
        } catch (err) {
            sentenceElement.textContent = "无法读取剪切板，请确保已授予权限";
            console.error('读取剪切板失败: ', err);
        }
    });
    
    // 重新读取剪切板内容
    reloadClipboardBtn.addEventListener('click', async function() {
        try {
            const text = await navigator.clipboard.readText();
            if (text) {
                processSentences(text);
            } else {
                sentenceElement.textContent = "剪切板为空，请复制内容后再试";
            }
        } catch (err) {
            sentenceElement.textContent = "无法读取剪切板，请确保已授予权限";
            console.error('读取剪切板失败: ', err);
        }
    });
    
    // 处理文本，分割成句子
    function processSentences(text) {
        // 使用正则表达式分割句子，保留分隔符
        // 匹配句号、问号、感叹号（中英文）以及额外的分隔符（\n、）、)）
        // 这里是添加额外分隔符的地方，可以在正则表达式中添加更多分隔符
        const regex = /([^。？！!?\n）)]+[。？！!?\n）)])/g;
        let tempSentences = [];
        
        let match;
        while ((match = regex.exec(text)) !== null) {
            tempSentences.push(match[0].trim());
        }
        
        // 处理可能没有结束符号的最后一句
        const lastPart = text.replace(regex, '').trim();
        if (lastPart) {
            tempSentences.push(lastPart);
        }
        
        // 如果没有找到句子，将整个文本作为一句
        if (tempSentences.length === 0 && text.trim()) {
            tempSentences.push(text.trim());
        }
        
        // 过滤掉无实际意义的内容
        sentences = tempSentences.filter(sentence => {
            // 去除空字符串
            if (!sentence || sentence.trim() === '') return false;
            
            // 去除只包含换行符的字符串
            if (sentence.trim() === '\n') return false;
            
            // 去除只包含空白字符的字符串
            if (/^\s+$/.test(sentence)) return false;
            
            // 去除只包含标点符号的字符串
            if (/^[。？！!?，,、；;：:""''「」『』（）()【】[\]{}]+$/.test(sentence)) return false;
            
            return true;
        });
        
        // 重置当前索引并显示第一句
        currentIndex = 0;
        
        // 如果过滤后没有内容，显示提示信息
        if (sentences.length === 0) {
            sentenceElement.textContent = "没有有效内容可显示";
            prevSentenceBtn.disabled = true;
            nextSentenceBtn.disabled = true;
            showProgressBtn.disabled = true;
            
            // 停止自动翻页
            if (autoNextTimer) {
                clearInterval(autoNextTimer);
                autoNextTimer = null;
                nextSentenceBtn.textContent = originalNextBtnText;
            }
        } else {
            updateSentenceDisplay();
            updateButtonStates();
            
            // 开始自动翻页倒计时
            startAutoNextCountdown();
        }
    }
    
    // 更新句子显示
    function updateSentenceDisplay() {
        if (sentences.length > 0) {
            // 使用marked解析Markdown内容
            sentenceElement.innerHTML = marked.parse(sentences[currentIndex]);
        } else {
            sentenceElement.textContent = "没有内容可显示";
        }
    }
    
    // 更新按钮状态
    function updateButtonStates() {
        prevSentenceBtn.disabled = currentIndex <= 0;
        nextSentenceBtn.disabled = currentIndex >= sentences.length - 1;
        
        // 只有当有句子时才启用显示进度按钮
        showProgressBtn.disabled = sentences.length === 0;
    }
    
    // 上一句按钮事件
    prevSentenceBtn.addEventListener('click', function() {
        if (currentIndex > 0) {
            currentIndex--;
            updateSentenceDisplay();
            updateButtonStates();
            
            // 重置自动翻页计时器
            startAutoNextCountdown();
        } else {
            showEndNotification();
        }
    });
    
    // 下一句按钮事件
    nextSentenceBtn.addEventListener('click', function() {
        if (currentIndex < sentences.length - 1) {
            currentIndex++;
            updateSentenceDisplay();
            updateButtonStates();
            
            // 重置自动翻页计时器
            startAutoNextCountdown();
        } else {
            showEndNotification();
        }
    });
    
    // 显示进度按钮事件（按下显示，松开隐藏）
    showProgressBtn.addEventListener('mousedown', function() {
        if (sentences.length > 0) {
            progressIndicator.textContent = `${currentIndex + 1}/${sentences.length}`;
            progressIndicator.style.display = 'block';
        }
    });
    
    showProgressBtn.addEventListener('mouseup', function() {
        progressIndicator.style.display = 'none';
    });
    
    showProgressBtn.addEventListener('mouseleave', function() {
        progressIndicator.style.display = 'none';
    });
    
    // 添加键盘导航支持
    document.addEventListener('keydown', function(event) {
        if (sentences.length === 0) return;
        
        if (event.key === 'ArrowLeft') {
            if (currentIndex > 0) {
                currentIndex--;
                updateSentenceDisplay();
                updateButtonStates();
                
                // 重置自动翻页计时器
                startAutoNextCountdown();
            } else {
                showEndNotification();
            }
        } else if (event.key === 'ArrowRight') {
            if (currentIndex < sentences.length - 1) {
                currentIndex++;
                updateSentenceDisplay();
                updateButtonStates();
                
                // 重置自动翻页计时器
                startAutoNextCountdown();
            } else {
                showEndNotification();
            }
        } else if (event.key === 'ArrowDown') { // 方向下键显示进度
            progressIndicator.textContent = `${currentIndex + 1}/${sentences.length}`;
            progressIndicator.style.display = 'block';
        } else if (event.key === 'ArrowUp') { // 方向上键增加计时10秒
            addCountdownTime(10);
        }
    });
    
    document.addEventListener('keyup', function(event) {
        if (event.key === 'ArrowDown') {
            progressIndicator.style.display = 'none';
        }
    });
});